package com.geping.etl.common.security.authentication.impl;

import com.geping.etl.common.entity.Sys_Auth_Role_Resource;
import com.geping.etl.common.security.authentication.AuthOrder;
import com.geping.etl.common.security.authentication.AuthOrderConstant;
import com.geping.etl.common.security.authentication.AuthServiceContainer;
import com.geping.etl.common.security.authentication.BasicAuthService;
import com.geping.etl.config.AuthConfigData;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class MenuApiAuthServiceImpl extends AuthServiceContainer implements BasicAuthService, AuthOrder,Comparable<AuthOrder>{


    /**
     * 判断接口权限
     * @param url
     * @return
     */
    @Override
    public boolean auth(String url,  HttpServletRequest request) {
        List<Sys_Auth_Role_Resource> resourceList = (List<Sys_Auth_Role_Resource>)request.getSession().getAttribute("resources");
        return hasAuthMenuApi(resourceList,url);
    }

    /**
     * 获取是否有接口权限
     * @return
     */
    private boolean hasAuthMenuApi(List<Sys_Auth_Role_Resource> resourceList,String url) {
        for(Sys_Auth_Role_Resource sysAuthRoleResource:resourceList){
            if(hasUrlAuth(sysAuthRoleResource,url)){
                return true;
            }
        }
        return false;
    }

    private boolean hasUrlAuth(Sys_Auth_Role_Resource sysAuthRoleResource, String url) {
        if(StringUtils.isNotBlank(sysAuthRoleResource.getResType())&&sysAuthRoleResource.getResType().equals("Menu")){
            List<String> authUrls= AuthConfigData.menuApiAuthData.get(sysAuthRoleResource.getResValueName());
            if(CollectionUtils.isEmpty(authUrls)){
                return false;
            }
            for(String authUrl:authUrls){
                if(authUrl.equals(url)){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return AuthOrderConstant.menuApiAuthService;
    }

    @Override
    public int compareTo(AuthOrder o) {
        return this.getOrder()-o.getOrder();
    }
}